import {
  getWarehouse,
  setWarehouse,
  removeWarehouse
} from '@/utils/warehouseAuth'

import {
  selectWarehouse
} from '@/api/wms/warehousePermission'
import { set } from '@/utils/db.js'

const getDefaultState = () => {
  return {
    warehouse: getWarehouse(),
    warehouseId: null,
    warehouseName: null
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_WAREHOUSE: (state, warehouse) => {
    state.warehouse = warehouse
  },
  SET_WAREHOUSE_ID: (state, warehouseId) => {
    state.warehouseId = warehouseId
  },
  SET_WAREHOUSE_NAME: (state, warehouseName) => {
    state.warehouseName = warehouseName
  }
}

const actions = {
  // select warehouse
  selectWarehouse({
    commit
  }, params) {
    return new Promise((resolve, reject) => {
      selectWarehouse({
        warehouseId: params
      }).then(response => {
        const {
          code,
          data
        } = response
        if (code === 1) {
          commit('SET_WAREHOUSE', data.token)
          commit('SET_WAREHOUSE_ID', data.warehouseId)
          commit('SET_WAREHOUSE_NAME', data.warehouseName)
          setWarehouse(data.token)
          set('warehouseName', data.warehouseName)
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  resetWarehouse({
    commit
  }) {
    return new Promise(resolve => {
      removeWarehouse()
      commit('RESET_STATE')
      resolve()
    })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
